#!/bin/bash

set -e

cd $(dirname $0)/..
BASEDIR=$(pwd)
mkdir -p $BASEDIR/build

function download_binary_unzip() {
    DRIVER_BINARY_NAME=$1
    DRIVER_MD5=$2
    DRIVER_DOWNLOAD_URL=$3

    if [[ $(curl -sSL $DRIVER_DOWNLOAD_URL | tee $DRIVER_BINARY_NAME | openssl md5 | sed 's/^.* //') != $DRIVER_MD5 ]]; then
        echo 'md5 checksum is wrong for '$DRIVER_BINARY_NAME
        exit 1
    fi

    if [ ${DRIVER_BINARY_NAME: -4} == ".zip" ]; then
        unzip -o $DRIVER_BINARY_NAME -d $BASEDIR/build/
    else
        # If the file isn't zippped
        cp $DRIVER_BINARY_NAME $BASEDIR/build/
        chmod 0755 $BASEDIR/build/$DRIVER_BINARY_NAME
    fi


    rm -rf $DRIVER_BINARY_NAME
}

function build_machine_binary() {
    mkdir -p $BASEDIR/build
    cd $BASEDIR/build

    MACHINE_REPOSITORY_URL=$1
    MACHINE_COMMIT_ID=$2

    rm -rf machine

    git clone $MACHINE_REPOSITORY_URL

    cd machine
    git checkout $MACHINE_COMMIT_ID
    TARGET_OS=linux TARGET_ARCH=${ARCH} ./script/build_in_container.sh build
    cp ./bin/docker-machine $BASEDIR/build/
    cd ..
    rm -rf machine
    cd $BASEDIR
}

build_machine_binary 'https://github.com/rancher/machine' 'v0.15.0-rancher20'

#download_binary_unzip 'packet-driver.zip' '2cd0b9614ab448b61b1bf73ef4738ab5' 'https://github.com/packethost/docker-machine-driver-packet/releases/download/v0.1.4/docker-machine-driver-packet_linux-amd64.zip'

mkdir -p $BASEDIR/dist/artifacts

cd $BASEDIR/build
tar -cvzf $BASEDIR/dist/artifacts/docker-machine-${ARCH}.tar.gz docker-machine
cp docker-machine* ../bin
